package com.shanjupay.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.convert.MerchantRegisterConvert;
import com.shanjupay.merchant.feign.MerchantFeign;
import com.shanjupay.merchant.service.FileService;
import com.shanjupay.merchant.service.SmsService;
import com.shanjupay.merchant.vo.MerchantRegisterVO;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

//为前端提供直接调用的接口
@RestController
@Api(value="商户平台应用接口",tags = "商户平台应用接口",description = "商户平台应用接口")
@RequestMapping("merchantApplication")
public class MerchantConterllor {

    @Autowired
    MerchantFeign merchantFeign;

    @Autowired
    SmsService smsService;

    @Autowired
    FileService fileService;

    //商户信息的注册接口
    @PostMapping("registerMerchant")
    public MerchantRegisterVO registerMerchant(@RequestBody MerchantRegisterVO merchantRegisterVO){
        //可以做一些非空校验
        Optional.ofNullable(merchantRegisterVO.getMobile()).orElseThrow(()->{ return new RuntimeException("请输入手机号");});
        Optional.ofNullable(merchantRegisterVO.getVerifiyCode()).orElseThrow(()->{ return new RuntimeException("请输入验证码");});
        Optional.ofNullable(merchantRegisterVO.getVerifiykey()).orElseThrow(()->{ return new RuntimeException("请输入验证码");});

        //校验验证码
        smsService.checkVerifiyCode(merchantRegisterVO.getVerifiykey(),merchantRegisterVO.getVerifiyCode());

        //调用feign接口去实现注册的功能
        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegisterVO);

        MerchantDTO merchantDTO1 = merchantFeign.registerMerchant(merchantDTO);

        return MerchantRegisterConvert.INSTANCE.dto2vo(merchantDTO1);
    }

    @PostMapping("sendMessage")
    public JSONObject sendMessage(HttpServletRequest request){
        //获取到手机号
        String mobile = request.getHeader("mobile");

        JSONObject jsonObject = smsService.sendMsg(mobile);

        return jsonObject;
    }

    //上传证件照接口
    @PostMapping("upload")
    public String upload(MultipartFile multipartFile) throws IOException {

        byte[] bytes = multipartFile.getBytes();
        String fileName= UUID.randomUUID().toString();
        return fileService.upload(bytes,fileName);
    }

}
